<?php
// +----------------------------------------------------------------------
// | 商家模块
// +----------------------------------------------------------------------

namespace app\mall\model;

use app\mall\model\Merch as MerchModel;
use app\mall\model\Store as StoreModel;
use app\mall\model\Goods as GoodsModel;
use app\mall\model\Cart as CartModel;
use app\user\model\Level;
use app\user\model\Member as MemberModel;
use app\user\model\User as UserModel;
use app\user\model\Vip as VipModel;
use app\user\model\Money as MoneyModel;
use app\user\model\Level as LevelModel;
use app\user\model\Rebate as RebateModel;
use think\Model as ThinkModel;
use think\facade\Db;
use util\Wxsdk;
use wxpay\PayVthree;

/**
 * 订单模型
 * @package app\mall\model
 */
class Order extends ThinkModel
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'mall_order';
		
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
	
	// 定义默认的表后缀
	protected $suffix = '';
	
	// 商户信息
	protected $merch;
	
	// 错误信息
	protected $error;
	
	/**
	 * 获取分页列表
	 * @return array|mixed
	 */
	public static function pageList($map = [], $order = [], $type='short', $page = 0, $from = 'web')
	{
		if ($page == 0) $page == config('paginate');
	    $data_list = self::where($map)->order($order)->paginate($page);
		if ($type == 'full') {
			foreach ($data_list as $key => $value) {
				$data_list[$key]['pay_price'] = $value['pay_price'] / 100;
				$data_list[$key]['balance'] = $value['balance'] / 100;
				$data_list[$key]['second'] = $value['second'] / 100;
				$data_list[$key]['realpay'] = $value['realpay'] / 100;
				$list = Db::view('mall_order_detail', true)
						->view("mall_goods", ['title','price','logo'], 'mall_goods.id=mall_order_detail.gid', 'left')
						->where('oid', '=', $value['id'])
						->select()
						->toArray();
				if ($from == 'api') {
					$data_list[$key]['cover'] = get_file_path(15);
					$data_list[$key]['url'] = real_url('mall/order/detail', ['id' => $value['id']]);
					$data_list[$key]['create_time'] = format_time($value['create_time']);
					$data_list[$key]['title'] = '商城订单';
					$data_list[$key]['pay_time'] = $value['pay_time'] == 0 ? '待支付' : format_time($value['pay_time']);
					foreach ($list as $k => $v) {
						$list[$k]['pay_price'] = $v['pay_price'];
						$list[$k]['balance'] = $v['balance'] / 100;
						$list[$k]['second'] = $v['second'] / 100;
						$list[$k]['realpay'] = $v['realpay'];
						$list[$k]['price'] = $v['pay_price'] * $v['number'];
						$list[$k]['cover'] = get_file_path($v['logo']);
					}
				}
				$data_list[$key]['list'] = $list;
			}
		}
	    return $data_list;
	}
	/**
	 * 创建订单
	 * @param int $carts 购物车信息
	 * @return array|mixed
	 */
	public function createOrder($cart_ids = [])
	{
		$uid = is_login();
		
		if ($uid <= 0) {
			$this->error = '用户信息错误';
			return false;
		}
		
		if ($cart_ids == []) {
			$this->error = '购物车参数错误';
			return false;
		}
		// 查找会员信息
		$vip = VipModel::where('member_id', '=', $uid)->where('status', '=', 1)->find();
		if (empty($vip)) {
			$this->error = 'vip资料错误';
			return false;
		}
		// 判断可以购买的商品
		$goods_ids = GoodsModel::where('status', '=', 1)->where('number', '>', 0)->column('id');
		
		if (empty($goods_ids)) {
			$this->error = '未找到可购买的商品';
			return false;
		}
		$carts = CartModel::where('id', 'in', $cart_ids)->where('uid', '=', $uid)->where('gid', 'in', $goods_ids)->select();
		
		if ($carts->isEmpty()){
			$this->error = '购物车信息错误';
			return false;
		}
        $vip = VipModel::where('member_id', '=', $uid)->find();
		$order_list = [];
		foreach ($carts as $key => $cart){
			$goods = GoodsModel::find($cart['gid']);
            if($vip['agent'] == 0){ //代理全部产品
                $goods['price'] = Level::pricefen_list($vip,$goods);
            }elseif($vip['agent'] == 1){ //代理泡浴类产品
                if($goods['agent'] == 1){
                    $goods['price'] = Level::pricefen_list($vip,$goods);
                }
            }elseif($vip['agent'] == 2){
                if($goods['agent'] == 2){
                    $goods['price'] = Level::pricefen_list($vip,$goods);
                }
            }
			// 判断商品库存
			if ($cart['number'] > $goods['number']) {
				$this->error = $goods['title'].'库存仅余：'.$goods['number'].', 请修改购买数量';
				return false;
			}
			// 判断是否限购
			if ($goods['canbuy'] > 0) {
				// 查找已有订单的商品数量
				$oids = self::where('uid', '=', $uid)->where('status', '>=', 1)->column('id');
				$nums = Db::name('mall_order_detail')->where('gid', '=', $cart['gid'])->where('oid', 'in', $oids)->sum('number');
				if ($nums + $cart['number'] > $goods['canbuy']) {
					$this->error = $goods['title'].'限购：'.$goods['canbuy'].'件, 你已购买'.$nums.'件，请修改数量。';
					return false;
				}
			}
			// 写入数组商品参数

            if($vip['group'] = 0){
                if($carts['number']>=5){
                    $carts[$key]['pay_price'] = $goods['price_pifa'] * $cart['number'];
                }
            }else{
                $carts[$key]['pay_price'] = $goods['price'] * $cart['number'];
            }

			$carts[$key]['discount'] = $goods['discount'];
			$carts[$key]['balance'] = $goods['balance'];
			$carts[$key]['money_se'] = $goods['money_se'];
			$carts[$key]['rebate'] = $goods['rebate'];
		}
		$goods_list = [];
		$money = $vip['money'];//首购余额
		$money_se = $vip['money_se'];//复购余额
		$shop = LevelModel::shopConfig($vip['shop']);
		foreach ($carts as $cart){
			$price = $cart['pay_price'];
			$balance = 0;
			$second = 0;
			$real_pay = 0;
			//当用户有余额且商品开启首购余额支付
            if($vip['group']>=2){
			if($money > 0 && $cart['balance'] == 1){
				if($cart['discount'] == 1){
					// 开启折扣
					if($money < $cart['pay_price'] * $shop['firstBuy'] / 100){
						// 首购+复购
						$balance = $money;
						$pay = round(($cart['pay_price'] - $money / $shop['firstBuy'] *100) * $shop['secondBuy'] /100 , 0);
						if ($pay <= $money_se) {
							$second = $pay;
							$money_se = $money_se - $pay;
							$real_pay = 0;
						} else {
							$money_se = 0;
							$second = $money_se;
							$real_pay = $pay - $money_se;
						}
						$money = 0;
					}else{
						// 单纯首购
						$balance = round($cart['pay_price'] * $shop['firstBuy'] / 100, 0);
						$pay = 0;
						$money = round($money - $cart['pay_price'] * $shop['firstBuy'] /100, 0);
					}
				}else{
					// 不折扣
					if($money < $cart['pay_price']){
						// 首购+复购
						$balance = $money;
						$pay = $cart['pay_price'] - $money;
						if ($pay <= $money_se) {
							$second = $pay;
							$money_se = $money_se - $pay;
							$real_pay = 0;
						} else {
							$money_se = 0;
							$second = $money_se;
							$real_pay = $pay - $money_se;
						}
						$money = 0;
					}else{
						// 单纯首购
						$balance = $cart['pay_price'];
						$pay = 0;
						$money = $money - $cart['pay_price'];
					}
				}
			// 商品未开启首购余额支付, 或用户无余额 按复购处理
			} else {
				// 开启打折
				if ($cart['discount'] == 1) {
					$balance = 0;
					$pay = round($cart['pay_price'] * $shop['secondBuy'] /100, 0);
				// 未开启打折
				} else {
					$balance = 0;
					$pay = $cart['pay_price'];
				}
				if ($pay <= $money_se) {
					$second = $pay;
					$real_pay = 0;
					$money_se = $money_se - $pay;
				} else {
					$second = $money_se;
					$real_pay = $pay - $money_se;
					$money_se = 0;
				}
			}
            }else{
                // 开启打折
                if ($cart['discount'] == 1) {
                    $balance = 0;
                    $pay = round($cart['pay_price'] * $shop['secondBuy'] /100, 0);
                    // 未开启打折
                } else {
                    $balance = 0;
                    $pay = $cart['pay_price'];
                }
                $real_pay = $pay;
                $second = 0;
            }

			$order_list[] = [
				'gid' 		=> $cart['gid'],
				'pay_price'	=> $balance + $second + $real_pay,
				'number'	=> $cart['number'],
				'discount'	=> round(($balance + $second + $real_pay) / $cart['pay_price'] * 100, 0),
				'balance'	=> $balance,
				'second'	=> $second,
				'realpay'	=> $real_pay,
				'remark'	=> $cart['remark'],
			];
			// 锁定库存
			$goods_list[$cart['gid']] = $cart['number'];
		}
		$order_info = [
			'pay_price'		=> array_sum(array_column($order_list, 'pay_price')),
			'sid'			=> 1,
			'uid'			=> $uid,
            'pay_name'		=> $vip['realname'],
			'number'		=> array_sum(array_column($order_list, 'number')),
			'balance'		=> array_sum(array_column($order_list, 'balance')),
			'second'		=> array_sum(array_column($order_list, 'second')),
			'realpay'		=> array_sum(array_column($order_list, 'realpay')),
		];
		// 判断是否强制提货
		if (app_config('mall', 'fullpay') == 1 && $vip['old'] == 0) {
			$order_payend = self::where('uid', '=', $uid)->where('status', '>', 0)->count('id');
			// 判断首次下单
			if (!$order_payend) {
				if ($order_info['balance'] < 1980000 && $vip['shop'] > 0) {
					$this->error = '店铺首次下单需订购满￥19800（折扣后）！当前折扣后￥'.$order_info['balance'] / 100 .'，还需：￥'. (1980000 - $order_info['balance']) / 100 .'；如有未支付订单，请先支付完成！';
					return false;
				}
			}
		}
		// 创建订单
		$order = self::create($order_info);
		if (!$order) {
			$this->error = '下单失败';
			return false;
		}
		foreach ($order_list as $key => $detail) {
			$order_list[$key]['oid'] = $order->id;
		}
		// 保存所有详情
		$orderModel = new self;
		$orderModel->setSuffix('_detail')->saveAll($order_list);
		
		// 减少商品库存
		foreach ($goods_list as $id => $number) {
			GoodsModel::where('id', '=', $id)->dec('number', $number)->update();
		}
		// 删除购物车
		$carts = CartModel::where('id', 'in', $cart_ids)->where('uid', '=', $uid)->delete();
		// 保存用户余额
		MoneyModel::moneyLog($uid, 4, $money - $vip['money'], $money_se - $vip['money_se'], 0, '订单ID：'.$order->id);
		return $order->id;
	}
	
	/**
	 * 请求支付订单
	 * @param int $id 订单id
	 * @return array|mixed
	 */
	public function payOrder($id = 0)
	{
		$order = self::find($id);
		$uid = is_login();
		if (!$order || $order['status'] > 0) {
			$this->error = '订单已失效或不可支付';
			return false;
		}
		// 检查交易金额
	    if ($order['realpay'] > 9999999) {
			$this->error = '交易金额错误';
			return false;
		}
		$address = VipModel::getAddress($uid);
		if ($address['complete'] == false) {
			$this->error = '请完善收货地址';
			return false;
		}
		// 查找发货仓商户
		$merch = StoreModel::where('id', '=', $order['sid'])->value('merch');
		
		if ($order['realpay'] <= 0) {
			// 直接更改支付状态
			$order->status = 1;
			$order->pay_time = time();
			$order->out_trade_no = date("YmdHis").rand(1000,9999);
			$order->mid = $merch;
			$order->save();
			Db::name('mall_order_detail')->where('oid', '=', $order['id'])->update(['status' => 1]);
			$this->error = 'success';
			return false;
		}
		
		if ($merch <= 0) {
			$this->error = '发货仓商户配置错误';
			return false;
		}
		
		$payer = MemberModel::getOpenid($uid);
		
		if ($payer == '') {
			$this->error = '用户信息错误';
			return false;
		}
		
		$merch_info = $this->merch;
		if (!$merch_info){
			$merch_info = MerchModel::getInfo($merch);
			$this->merch = $merch_info;
		}
		if (!$merch_info) {
			$this->error = '商户不存在';
			return false;
		}
		if (!$merch_info['wxpay_id']){
			$this->error = '微信商户号未设置';
			return false;
		}
		$trade = date("YmdHis").rand(1000,9999);
		$param = [
			'appid'			=>  config('wechat.appid'),
			'out_trade_no'	=> (string)$trade,
			'mchid'			=> (string)$merch_info['wxpay_id'],
			'description'	=> $merch_info['short_name'].'商品订单',
			'attach'		=> (string)$merch,
			'amount'		=> ['total' => $order['realpay'], 'currency' => 'CNY'],
			'payer'			=> ['openid' => $payer],
			'scene_info'	=> ['payer_client_ip' => get_client_ip(), 'device_id' => (string)$merch_info['id']],
		];
		
		$pay = new PayVthree(true, $merch);

		$return = $pay->transactions($param);

		$sign = [];
		if ($return['code'] == 200) {
			$sign = [
				'appId' 	=> $param['appid'],
				'timeStamp'	=> (string)time(),
				'nonceStr'	=> generate_rand_str(32),
				'package'	=> 'prepay_id='.$return['data']['prepay_id'],
				'signType'	=>	'RSA',
                'openid'    =>$payer,
                'out_trade_no'=>$trade,
                'description'	=> $merch_info['short_name'].'商品订单',
                'amount'		=> $order['realpay'],
			];
			$message = $sign['appId']."\n".
			$sign['timeStamp']."\n".
			$sign['nonceStr']."\n".
			$sign['package']."\n";
			$sign['paySign'] = $pay->sign($message);
			$order->mid = $merch;
			$order->out_trade_no = $trade;
			$order->save();
			return $sign;
		} else {
			$this->error = '请求下单API错误';
			return false;
		}
	}
	
	/**
	 * 订单退款
	 * @param int out_trade_no 商户订单号
	 * @return array|mixed
	 */
	public function refund($out_trade_no, $money = 0)
	{
		$order = self::where('out_trade_no', '=', $out_trade_no)->find();
		
		if (!$order) {
			$this->error = '该订单不存在';
			return false;
		}

		if($order['status'] <= 0){
			$this->error = '该订单不允许退款';
			return false;
		} 
		if($order['refund'] == $order['realpay']){
			$this->error = '该订单已全额退款';
			return false;
		}
		// 判断订单时间是否超过2个月
		if ($order['create_time'] < time() - 3600*24*60) {
			$this->error = '系统不支持超过60天的订单退款';
			return false;
		}
		if ($money > 0) {
			if ($money * 100 > $order['realpay']){
				$this->error = '退款金额不能超过订单金额';
				return false;
			}
			$refund_money = $money * 100;
		} else {
			$refund_money = $order['realpay'];
		}
		$out_refund_no = (string)date("YmdHis").rand(1000,9999);
		// 微信订单
		$param = [
			'out_trade_no'	=> (string)$order['out_trade_no'],
			'out_refund_no'	=> $out_refund_no,
			'amount'		=> ['refund' => $refund_money,'total' => $order['realpay'], 'currency' => 'CNY'],
		];
		$pay = new PayVthree(true, $order['mid']);
		$return = $pay->transactions($param, 'refund');
		if ($return['code'] == 200) {
			$order->status = 4;
			$order->refund = ['inc', $refund_money];
			$order->out_refund_no = $out_refund_no;
			$order->refund_time = time();
			$order->save();
			return true;
		} else {
			$this->error = $return['msg'];
			return false;
		}
	}
	/**
	 * 撤销订单
	 * @param int id 订单id号
     * * @param int types 订单狀態
	 * @return array|mixed
	 */
	public function cancel($id)
	{
		$order = self::where('id', '=', $id)->find();
		if (!$order) {
			$this->error = '该订单不存在';
			return false;
		}

		if($order['status'] > 1 && $order['status']!= 5){
			$this->error = '该订单不允许撤销';
			return false;
		}
		if($order['status'] == 5){
            if ($order['balance'] > 0 || $order['second'] > 0) { //返回订单余额
                $log = MoneyModel::moneyLog($order['uid'], 2, $order['balance'], $order['second'], 0);
                if (!$log){
                    $this->error = '保存用户余额失败';
                    return false;
                }
            }
            //删除订单
            $detail_list = Db::name('mall_order_detail')->where('oid', '=', $order['id'])->select();
            foreach ($detail_list as $detail) {
                $goods = GoodsModel::where('id', '=', $detail['gid'])->find();
                if ($goods) {
                    $goods->number = ['inc', $detail['number']];
                    $goods->save(); //返回库存；
                }
//                Db::name('mall_order_detail')->where('id', '=', $detail['id'])->delete();
            }

            // 已支付订单 微信支付原路退回
            if ($order['status'] == 1 && $order['realpay'] > 0 && $order['out_trade_no'] > 0) {
                $this->refund($order['out_trade_no']);
            }
            $data['status'] = 6;
            self::where('id', '=', $id)->update($data);
            return true;
//            return $order->delete();

        }else{
            $data['status'] = 5;
            self::where('id', '=', $id)->update($data);
            $data_list = Db::name('admin_user')->where('role', '=', 6)->select()->toArray();
//            var_dump($data_list);exit;
            foreach ($data_list as $v){

                if(!empty($v['openid'])){
                    $sendData = [
                        'template_id'   => '1aYunv430Dy6I0fe8Tc7gQbSd41i9dljUF8f5pkNL0c',//模板消息ID
                        'touser'    => $v['openid'],//用户openid：o25FHswdGhUZSuLR12d_UXreGr3w
                        'data'=>[
                            'first'=>[
                                'value'=>'您有新的订单待处理',
                                'color'=>'#000000',
                            ],
                            'keyword1'=>[
                                'value'=>'订单编码：'.$order['id'],//订单编号
                                'color'=>'#000000'
                            ],
                            'keyword2'=>[//订单金额
                                'value'=>number_format($order['realpay']/100,2),
                                'color'=>'#000000'
                            ],
                            'keyword3'=>[//创建时间
                                'value'=>date('Y-m-d H:i:s',time()),
                                'color'=>'#000000'
                            ],
                            'remark'=>[
                                'value'=>'取消订单待审核！',//描述
                                'color'=>'#173177',
                            ],
                        ]
                    ];
                    $this->template($sendData);
                }
            }

            return true;
        }
	}
    /**
     * 驳回订单
     * @param int id 订单id号
     * @return array|mixed
     */

	public function cancel_live($id){
        $order = self::where('id', '=', $id)->find();
        $data['status'] = 1;
        self::where('id', '=', $id)->update($data);
        $data_list = Db::name('admin_user')->where('role', '=', 6)->select()->toArray();
//            var_dump($data_list);exit;
        foreach ($data_list as $v){

            if(!empty($v['openid'])){
                $sendData = [
                    'template_id'   => '1aYunv430Dy6I0fe8Tc7gQbSd41i9dljUF8f5pkNL0c',//模板消息ID
                    'touser'    => $v['openid'],//用户openid：o25FHswdGhUZSuLR12d_UXreGr3w
                    'data'=>[
                        'first'=>[
                            'value'=>'您有新的订单待处理',
                            'color'=>'#000000',
                        ],
                        'keyword1'=>[
                            'value'=>'订单编码：'.$order['id'],//订单编号
                            'color'=>'#000000'
                        ],
                        'keyword2'=>[//订单金额
                            'value'=>number_format($order['realpay']/100,2),
                            'color'=>'#000000'
                        ],
                        'keyword3'=>[//创建时间
                            'value'=>date('Y-m-d H:i:s',time()),
                            'color'=>'#000000'
                        ],
                        'remark'=>[
                            'value'=>'驳回订单待发货！',//描述
                            'color'=>'#173177',
                        ],
                    ]
                ];
                $this->template($sendData);
            }
        }

        return true;
    }
	/**
	 * 确认收货
	 * @param int id 订单id号
	 * @return array|mixed
	 */
	public function action($id)
	{
		$order = self::where('id', '=', $id)->find();
		if (!$order) {
			$this->error = '该订单不存在';
			return false;
		}
	
		if($order['status'] != 2){
			$this->error = '该订单不允许确认收货';
			return false;
		}
        $vip = VipModel::where('member_id', '=', $order['uid'])->find();
        $p_user = VipModel::where('member_id', '=', $vip['pid'])->find();
        if($vip['group']>=$p_user['group']){
            // 判断用户支付方式 及系统是否开启返佣
            if ($order['second'] + $order['realpay'] > 0 && app_config('mall', 'rebate') == 1) {
                // 处理返佣
                $rebate_goods = cache('rebate_goods');
                if (!$rebate_goods) {
                    $rebate_goods = GoodsModel::where('rebate', '=', 1)->column('id');
                    cache('rebate_goods', $rebate_goods, 600);
                }
                if ($rebate_goods) {
                    // 查找待返佣的商品订单
                    $rebate_money = Db::name('mall_order_detail')->where('oid', '=', $order['id'])->where('gid', 'in', $rebate_goods)->field('sum(second) as second, sum(realpay) as realpay')->find();
                    if ($rebate_money['second'] + $rebate_money['realpay'] > 0) {
                        $rebate = new RebateModel;
                        $rebate->saveData($order['uid'], 2, 2, $rebate_money['second'] + $rebate_money['realpay'] , $order['id']);

                    }
                }
            }
        }
		//保存订单状态
		$order->status = 3;
		return $order->save();
	}
	/**
	 * 订单详情
	 * @param int id 订单ID号
	 * @return array|mixed
	 */
	public function detail($id)
	{
		$order = self::where('id', '=', $id)->find();
		if (!$order) {
			$this->error = '该订单不存在';
			return false;
		}
		$order = $order->toarray();
		$order['detail'] = Db::view('mall_order_detail', true)
						->view("mall_goods", ['title','price','logo'], 'mall_goods.id=mall_order_detail.gid', 'left')
						->where('oid', '=', $id)
						->select()
						->toArray();
		return $order;
	}
	/**
	 * 处理支付通知
	 * @param int $id 类型id
	 * @author paulxun
	 * @return array
	 */
	public function notify($data = [], $type = 'wechat')
	{
	    if ($data == []) {
			$this->error = '参数错误';
	        return false;
	    }
		if ($type === 'wechat'){
			if (!isset($data['out_trade_no']) || !isset($data['trade_state'])){
				$this->error = '订单不存在';
				return false;
			}
			$order = self::where('out_trade_no', '=', $data['out_trade_no'])->find();
			if (!$order) return false;
			
			switch ($data['trade_state']) {
				case 'SUCCESS' :
				$status = 1;
				break;
				case 'REFUND' :
				$status = 4;
				break;
				default :
				$status = 0;
				return true;
			}
			if ($order['status'] == 0) {
				// 保存用户记录
				MoneyModel::moneyLog($order['uid'], 4, 0, 0, $order['realpay'], '订单ID：'.$order['id']);
			}
			$order->status = $status;
			$order->pay_time = time();
			$order->save();
			Db::name('mall_order_detail')->where('oid', '=', $order['id'])->update(['status' => 1]);
		}
	    return true;
	}
	/**
	 * 检查订单
	 * @param int $array 订单数据
	 * @author paulxun
	 * @return array
	 */
	public function checkOrder($id)
	{
		$order = self::where('id', $id)->where('status', 0)->find();
		if ($order) {
			// 查询订单
			if ($order['realpay'] > 0 && $order['out_trade_no'] > 0) {
				$return = $this->tradeQuery($order['out_trade_no']);
				if (!$return) {
					return $this->cancel($id);
				} else {
					return false;
				}
			} else {
				return $this->cancel($id);
			}
		} else {
			return false;
		}
	}
	/**
	 * 订单查询
	 * @param int out_trade_no 商户订单号
	 * @return array|mixed
	 */
	public function tradeQuery($out_trade_no)
	{
		$order = self::where('out_trade_no', '=', $out_trade_no)->find();
		if (!$order) {
			$this->error = '该订单不存在';
			return false;
		}
		if ($order['realpay'] <= 0) {
			$this->error = '该订单未使用微信支付';
			return false;
		}
		// 微信查询订单参数
		$param = [
			'out_trade_no'	=> (string)$order['out_trade_no'],
		];
		$pay = new PayVthree(true, $order['mid']);
		$return = $pay->transactions($param, 'query');
		
		if ($return['code'] == 200) {
			$this->notify($return['data'], 'wechat');
		} else {
			$this->error = $return['msg'];
			return false;
		}
	}
	/**
	 * 订单打印
	 * @param  array 订单数据
	 * @param  array child_info 商户终端数据
	 * @return array|mixed
	 */
	public function printTxt($array, $child_info, $print_audio = true)
	{
		$elind = new Elind();
		$content  = "<MN>1</MN>";
		$audio = "<audio>您有一笔新订单,5,0</audio>";
		if ($array['type'] == 1 && $child_info['print_money'] == 1 && $print_audio == true) {
			$audio = "<audio>微信到账". $array['total'] / 100 ."元,5,0</audio>";;
		}
		if ($array['type'] == 2 && $child_info['print_money'] == 1 && $print_audio == true) {
			$audio = "<audio>支付宝到账". $array['total'] / 100 ."元,5,0</audio>";;
		}
		$content .= $audio;
		$content .= "<FS2><center>**". $child_info['merch']."**</center></FS2>";
		$content .= str_repeat('.', 32);
		$content .= "<FS><center>--".$child_info['name'] ."--</center></FS>";
		$content .= "订单时间:". format_time($array['pay_time']) . "\n";
		$content .= "订单编号:". $array['out_trade_no']."\n";
		$content .= "支付类型:". self::types($array['type'])."\n";
		$content .= "支付方式:". self::from($array['from'])."\n";
		$content .= "支付状态:". self::status($array['status'])."\n";
		$content .= str_repeat('.', 32);
		$content .= "支付金额:￥".$array['total'] / 100 ."元 \n";
		$content .= "\n";
		$content .= "<QR>".real_url('merch/order/detail', ['trade' => $array['out_trade_no']])."</QR>";
		$content .= "打印时间:". format_time(time()) ."\n";
		$content .= str_repeat('*', 32);
		$content .= "备注:". $array['remark']."\n";
		$content .= "\n";
		return $elind->printTxt($child_info['print_id'], $content, $array['out_trade_no']);
	}
	
	/**
	 * 支付状态
	 * @param int $id 类型id
	 * @author paulxun
	 * @return array|static
	 */
	public static function status($id = 9)
	{
		$types = [
			0 => '未支付',
			1 => '待发货',
			2 => '待收货',
			3 => '已完成',
            5 => '待审核',
            6 => '已取消',
			// 4 => '已退款',
		];
	    if ($id === 9) {
	        $result = $types;
	    }else{
			$result = '';
			if(isset($types[$id])) $result = $types[$id];
		}
	    return $result;
	}
	
	/**
	 * 快递列表
	 * @param int $id 类型id
	 * @author paulxun
	 * @return array|static
	 */
	public static function express($id = 9)
	{
		$types = [
			'annengwuliu' => '安能物流',
			'htky' => '百世快递',
			'zhongtong' => '中通快递',
			'jitu' => '极兔快递',
			'shunfeng' => '顺丰快递',
			'sf'		=> '顺丰速运',
			// 4 => '已退款',
		];
	    if ($id === 9) {
	        $result = $types;
	    }else{
			$result = '';
			if(isset($types[$id])) $result = $types[$id];
		}
	    return $result;
	}
	
	/**
	 * 获取错误信息
	 * @access public
	 * @return mixed
	 */
	public function getError()
	{
	    return $this->error;
	}

    // 发送微信模板消息
    protected function template($data)
    {
        $wxsdk = new Wxsdk;
        return $wxsdk->template($data);
    }
}
